import React from 'react';

import { Modal, Form, Input, notification as Notification } from 'antd';

import { FormInstance } from 'antd/lib/form';
import PropTypes from 'prop-types';
import { saveBookClassification, updateBookClassification } from '../../../../api/bookClassification';

class BookClassificationForm extends React.Component {
  state = {
    visible: false,
    type: 'add',
    data: {},
  };

  formRef = React.createRef(FormInstance);

  constructor(props) {
    super(props);
    const { visible, data, type } = props;
    this.state = {
      visible,
      data,
      type,
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    const state = Object.assign(this.state, JSON.parse(JSON.stringify(nextProps)));
    this.setState(state);
  }

  saveOrUpdate = () => {
    const form = this.formRef.current;
    const { type, data } = this.state;

    form.validateFields().then((values) => {
      if (type === 'add') {
        values.pid = data.id;
        saveBookClassification(values).then(({ data }) => {
          Notification.success({
            message: `添加${data.name}成功`,
            duration: 2
          });
          this.onClose();
        }).catch((e) => {
          console.log(e, typeof e, 'e');
        });
      } else if (type === 'edit') {
        Object.assign(data, values);
        updateBookClassification(data).then(({ data }) => {
          Notification.success({
            message: `更新${data.name}成功`,
            duration: 2
          });
          this.onClose();
        }).catch((e) => {
          console.log(e, typeof e, 'e');
        });
      }
    }).catch((errorInfo) => {
      const { errorFields } = errorInfo;
      Notification.error({
        message: errorFields[0].errors[0],
        duration: 2
      });
    });
  };

  onClose = () => {
    const { onClose } = this.props;
    if (typeof onClose === 'function') {
      onClose();
    }
  };

  render() {
    const { visible, type, data } = this.state;
    const disabled = type === 'detail';
    const initialValues = type === 'add' ? {} : data;

    const titleMapping = {
      add: '新增书籍分类',
      edit: '修改书籍分类',
      detail: '书籍分类详情',
    };

    return (
      <Modal
        visible={visible}
        destroyOnClose
        title={titleMapping[type] || '新增'}
        okText="确定"
        cancelText="取消"
        onCancel={this.onClose}
        onOk={this.saveOrUpdate}
        maskClosable={false}
      >
        <Form
          ref={this.formRef}
          {
            ...{
              labelCol: { span: 6 },
              wrapperCol: { span: 18 },
            }
          }
          name="editForm"
          initialValues={{ ...initialValues }}
          scrollToFirstError
        >
          <Form.Item
            name="classification"
            label="分类法序号"
            hasFeedback
            hidden={disabled}
            rules={[
              {
                required: true,
                message: '请输入书籍分类名称!',
                whitespace: true
              }
            ]}
          >
            <Input/>
          </Form.Item>
          <Form.Item
            name="name"
            label="书籍分类名称"
            hasFeedback
            hidden={disabled}
            rules={[
              {
                required: true,
                message: '请输入书籍分类名称!',
                whitespace: true
              }
            ]}
          >
            <Input/>
          </Form.Item>
          <Form.Item name='remark' label="备注">
            <Input.TextArea/>
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

BookClassificationForm.propTypes = {
  visible: PropTypes.bool.isRequired,
  type: PropTypes.string.isRequired,
  data: PropTypes.object,
  onClose: PropTypes.func.isRequired
};

export default BookClassificationForm;
